<template>
  <div>
    <div v-for="(item, index) in mainList" :key="index" class="expense-item">
      <flexbox class="expense-item-head">
        <div class="expense-item-head-title">
          {{ $t('oa.examine.92974b0740a22c097628f2578e224b75',{1: index+1 }) }}
        </div>
        <el-button
          v-if="index != 0 && !config.table.delDisabled"
          type="text"
          class="el-icon-delete expense-item-head-delete"
          @click="deleteItems(index)" />
      </flexbox>
      <flexbox wrap="wrap" align="stretch" class="clauses">
        <flexbox-item
          v-for="(subItem, subIndex) in showItems"
          :key="subIndex"
          :span="1/2"
          class="clauses-item">
          <div class="clauses-item-title">
            {{ subItem.name }}
          </div>
          <el-date-picker
            v-if="subItem.formType == 'datetime'"
            v-model="item[subItem.field]"
            :disabled="subItem.disabled"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            :placeholder="$t('oa.examine.311a57e9e3e19eeaf032eb495fb3acab')"
            @change="valueChange" />
          <el-input-number
            v-else-if="subItem.formType == 'number'"
            v-model="item[subItem.field]"
            :disabled="subItem.disabled"
            :controls="false"
            :precision="2"
            :min="0"
            @input="calculateValueChange(index, subIndex)" />
          <el-input
            v-else
            v-model="item[subItem.field]"
            :disabled="subItem.disabled"
            :maxlength="100"
            type="text"
            @input="calculateValueChange(index, subIndex)" />
        </flexbox-item>
        <flexbox-item
          v-if="config.showSubTotal"
          :span="1/2"
          class="clauses-item">
          <div class="sub-total">
            {{ $t('oa.examine.ef5d336b113cd3ad149817210dbaca89') }}
            <span>{{ item['money'] }}</span>
          </div>
        </flexbox-item>
      </flexbox>
      <div
        v-if="!config.field || config.field.hasOwnProperty('description')"
        class="description">
        <div class="description-title">{{ $t('oa.examine.1b3223b288daaa4c6ac25f4a5d238da9') }}</div>
        <el-input
          v-model="item['description']"
          :rows="3"
          :maxlength="300"
          :disabled="config.field ? config.field.description : false"
          type="textarea"
          resize="none"
          show-word-limit
          @input="valueChange" />
      </div>
      <div
        v-if="!config.field || config.field.hasOwnProperty('file')"
        class="files">
        <el-button
          v-if="!config.field || !config.field.file"
          type="text"
          class="add-files"
          @click="addFiles(index)">{{ $t('oa.examine.bf2440c0ff255edbe8c45b6f12a6b872') }}</el-button>
        <flexbox wrap="wrap">
          <div
            v-for="(imgItem, imgIndex) in item['imgList']"
            :key="imgIndex"
            v-src:background-image="imgItem.url"
            class="img-item"
            @mouseover="mouseImgOver(imgItem, imgIndex, item['imgList'])"
            @mouseleave="mouseImgLeave(imgItem, imgIndex, item['imgList'])">
            <div
              v-if="imgItem.showDelete && (!config.field || !config.field.file)"
              class="img-delete"
              @click="deleteFile(imgItem, imgIndex, item['imgList'])">
              ×
            </div>
          </div>
        </flexbox>
      </div>
    </div>
    <div class="handle-bar">
      <el-button
        v-if="!config.table.addDisabled"
        class="handle-bar-button"
        type="text"
        @click="addItems(index)">{{ $t('oa.examine.15f38b413fbd3e8a3d54787946ec1a83') }}</el-button>
        <!-- <div class="handle-bar-total">
        合计（元）：<span>{{totalMoney}}</span>
      </div> -->
    </div>
    <input
      id="image-file-input"
      type="file"
      accept="image/*"
      multiple
      @change="uploadImageFile">
  </div>
</template>

<script type="text/javascript">
import { crmFileSaveAPI, crmFileDeleteAPI } from '@/api/common'
import ObjMixin from '@/components/CreateCom/ObjMixin'
import { guid, floatAdd } from '@/utils'
import merge from '@/utils/merge'

export default {
  name: 'XhExpenses', // 差旅报销事项
  components: {},
  mixins: [ObjMixin],
  props: {
    props: Object
  },
  data() {
    return {
      mainList: [],
      imageIndex: -1,
      totalMoney: '0' // 合计
    }
  },
  computed: {
    config() {
      return merge({
        table: {
          addDisabled: false,
          delDisabled: false
        }, // addDisabled delDisabled
        field: null, // null 不拦截 没有的键不展示 true值禁止操作 false 可编辑
        showSubTotal: true
      }, this.props || {})
    },

    showItems() {
      const defaultList = [
        {
          field: 'startAddress',
          name: this.$t('oa.examine.8966d85e82f930f0b8c3fd1cfd520460'),
          formType: 'text'
        },
        {
          field: 'endAddress',
          name: this.$t('oa.examine.8d33d9e782c68f0ed542558e77be0d37'),
          formType: 'text'
        },
        {
          field: 'startTime',
          name: this.$t('oa.examine.8069835459dc2c92273b1fffbc0834b3'),
          formType: 'datetime'
        },
        {
          field: 'endTime',
          name: this.$t('oa.examine.c0563e1a287b18af68bbc54e0a2cfcb2'),
          formType: 'datetime'
        },
        {
          field: 'traffic',
          name: this.$t('oa.examine.aea056d01bbf2b69a0482457068bc3b9'),
          formType: 'number'
        },
        {
          field: 'stay',
          name: this.$t('oa.examine.f43084539096e621a080d4da385208b0'),
          formType: 'number'
        },
        {
          field: 'diet',
          name: this.$t('oa.examine.84675e079e366ee6d210545523228068'),
          formType: 'number'
        },
        {
          field: 'other',
          name: this.$t('oa.examine.8283cbfb480e79cf68257cbb796fa38a'),
          formType: 'number'
        }
      ]

      const filedConfig = this.config.field
      if (filedConfig) {
        const validList = []
        defaultList.forEach(item => {
          if (typeof filedConfig[item.field] === 'boolean') {
            item.disabled = filedConfig[item.field]
            validList.push(item)
          }
        })
        return validList
      }

      return defaultList
    }
  },
  watch: {
    value: function(val) {
      this.dataValue = val
      if (val.list && val.list.length > 0) {
        this.mainList = val.list
      } else {
        this.mainList.push(this.getValueItem())
      }
    }
  },
  mounted() {
    if (this.dataValue.list && this.dataValue.list.length > 0) {
      this.mainList = this.dataValue.list
    } else {
      this.mainList.push(this.getValueItem())
    }
  },
  methods: {
    addFiles(index) {
      this.imageIndex = index
      document.getElementById('image-file-input').click()
    },
    /** 图片选择出发 */
    uploadImageFile(event) {
      var files = event.target.files

      for (let index = 0; index < files.length; index++) {
        const file = files[index]
        crmFileSaveAPI({
          type: 'img',
          file: file,
          batchId: this.mainList[this.imageIndex].batchId
        })
          .then(res => {
            if (res) {
              this.mainList[this.imageIndex].imgList.push(res.data || {})
              this.submitValueChange()
            }
          })
          .catch(() => {})
      }
      event.target.value = ''
    },
    /** 鼠标移入和移除 图片区域 */
    mouseImgOver(item, index, items) {
      item.showDelete = true
      this.$set(items, index, item)
    },
    mouseImgLeave(item, index, items) {
      item.showDelete = false
      this.$set(items, index, item)
    },
    deleteFile(item, index, items) {
      this.$confirm(
        this.$t('oa.examine.8ac0d2df778874f4148e5394d2ec047a'),
        this.$t('oa.examine.29234b5564997887b9ea5a1c1e24d1cd'),
        {
          confirmButtonText: this.$t('oa.examine.f46e3cf16c8c1cf9da34ace0b184b5b0'),
          cancelButtonText: this.$t('oa.examine.d93afd75d141603afffcd1b786df26b6'),
          type: 'warning'
        }
      )
        .then(() => {
          crmFileDeleteAPI({
            id: item.fileId
          })
            .then(res => {
              items.splice(index, 1)
              this.$message.success(this.$t('oa.examine.07f3a8aae7f98afbdf3e6e408c642b8d'))
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    deleteItems(index) {
      this.mainList.splice(index, 1)
      // 更新合计值
      this.updateTotalValue()
      this.submitValueChange(true)
    },
    addItems() {
      this.mainList.push(this.getValueItem())
    },
    valueChange() {
      this.submitValueChange(false)
    },
    // 值更新的回调
    calculateValueChange(mainIndex, subIndex) {
      if (subIndex < 2) {
        this.submitValueChange(false)
        return
      }

      // 不展示合计，也就是审批字段授权处，不需要计算合计
      if (this.config.showSubTotal) {
        var subTotal = 0
        const calculateFields = ['traffic', 'stay', 'diet', 'other']
        const mainItem = this.mainList[mainIndex]
        calculateFields.forEach(field => {
          subTotal = floatAdd(
            subTotal,
            parseFloat(mainItem[field] ? mainItem[field] : 0)
          )
        })
        mainItem.money = subTotal
        // 更新合计值
        this.updateTotalValue()

        this.submitValueChange(true)
      }
    },

    /**
     * 更新合计
     */
    updateTotalValue() {
      let total = 0
      for (let index = 0; index < this.mainList.length; index++) {
        const element = this.mainList[index]
        total = floatAdd(
          total,
          parseFloat(element.money ? element.money : 0)
        )
      }
      this.totalMoney = total
    },

    submitValueChange(update) {
      this.$emit('value-change', {
        index: this.index,
        value: {
          list: this.mainList,
          update: update, // 是否更新总数
          money: this.totalMoney
        }
      })
    },
    getValueItem() {
      const defaultItem = {
        startAddress: '',
        endAddress: '',
        startTime: '',
        endTime: '',
        traffic: '',
        stay: '',
        diet: '',
        other: '',
        money: '0',
        description: '',
        imgList: [],
        batchId: guid()
      }

      console.log('this.config.showSubTotal---', this.config.showSubTotal)
      if (!this.config.showSubTotal) {
        delete defaultItem.money
      }

      return defaultItem
    }
  }
}
</script>

<style lang="scss" scoped>
.expense-item {
  padding-bottom: 15px;
  margin-bottom: 10px;
  border: $--border-width-medium solid $--border-color-base;
  border-radius: 2px;

  &-head {
    padding: 10px 20px;
    background-color: #f5f5f5;

    &-title {
      flex: 1;
      height: auto;
      line-height: normal;
    }

    &-delete {
      padding: 0 10px;
      cursor: pointer;
    }
  }
}

.clauses {
  padding: 10px;

  &-item {
    display: flex;
    padding: 0 10px 8px;
    margin-left: 0 !important;

    &-title {
      flex-shrink: 0;
      width: 90px;
    }

    .el-date-editor,
    .el-select {
      width: 100%;
    }

    .el-input-number {
      width: 100%;

      ::v-deep .el-input__inner {
        padding: 0 8px;
        text-align: left;
      }
    }
  }
}

.sub-total {
  font-size: 12px;
}

.description {
  padding: 0 20px;

  &-title {
  }
}

.el-input ::v-deep .el-input__inner {
  border-color: #ddd !important;
}

.el-select ::v-deep .el-input__inner {
  border-color: #ddd !important;
}

.el-textarea ::v-deep .el-textarea__inner {
  border-color: #ddd !important;
}

.el-input-number ::v-deep .el-input__inner {
  border-color: #ddd !important;
}

.handle-bar {
  height: 29px;
  text-align: right;

  &-button {
    padding-right: 0;
    border: none;
  }

  &-total {
    margin-top: 10px;
    font-size: 13px;
    text-align: left;

    span {
      color: $--color-text-regular;
    }
  }
}

.files {
  padding: 0 20px;

  .add-files {
    padding-left: 0;
  }
}

.img-item {
  position: relative;
  display: inline-block;
  width: 98px;
  height: 98px;
  margin: 0 4px 4px 0;
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  border: 1px solid #ccc;

  .img-delete {
    position: absolute;
    top: 0;
    right: 0;
    width: 20px;
    height: 20px;
    font-size: 17px;
    line-height: 20px;
    color: white;
    text-align: center;
    cursor: pointer;
    background-color: $--color-text-regular;
  }
}

#image-file-input {
  display: none;
}
</style>
